<template>
  <div class="dashboard-container" id="food-app">
    <div class="container">
      <div class="tableBar">
        <el-input
            v-model="input"
            placeholder="请输入菜品名称"
            style="width: 250px"
            clearable
            @keyup.enter="handleQuery"
        >
          <template #prefix>
            <i class="el-input__icon el-icon-search" style="cursor: pointer" @click="init"></i>
          </template>
        </el-input>

        <div class="tableLab">
          <el-button type="text" class="span-btn delBut non" @click="deleteHandle('批量', null)">批量删除</el-button>
          <el-button type="text" class="span-btn blueBug non" @click="statusHandle('1')">批量启售</el-button>
          <el-button type="text" class="span-btn delBut non" @click="statusHandle('0')">批量停售</el-button>
          <el-button type="primary" @click="addFoodtype('add')">+ 新建菜品</el-button>
        </div>
      </div>

      <el-table :data="tableData" stripe class="tableBox" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="25"></el-table-column>
        <el-table-column prop="name" label="菜品名称"></el-table-column>

        <el-table-column prop="image" label="图片" align="center">
          <template #default="{ row }">
            <el-image
                style="width: auto; height: 40px; border:none; cursor: pointer;"
                :src="getImage(row.image)"
                :preview-src-list="[ `/common/download?name=${row.image}` ]"
            >
              <template #error>
                <div class="image-slot">
                  <img src="../../../../images/noImg.png" style="width: auto; height: 40px; border:none;">
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="categoryName" label="菜品分类"></el-table-column>
        <el-table-column label="售价">
          <template #default="{ row }">
            <span style="margin-right: 10px;">￥{{ row.price / 100 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售卖状态">
          <template #default="{ row }">
            <span style="margin-right: 10px;">{{ row.status === 0 ? '停售' : '启售' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间"></el-table-column>

        <el-table-column label="操作" width="160" align="center">
          <template #default="{ row }">
            <el-button type="text" size="small" class="blueBug" @click="addFoodtype(row.id)">修改</el-button>
            <el-button type="text" size="small" class="blueBug" @click="statusHandle(row)">
              {{ row.status === 0 ? '启售' : '停售' }}
            </el-button>
            <el-button type="text" size="small" class="delBut non" @click="deleteHandle('单删', row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pageList"
          :page-sizes="[10, 20, 30, 40]"
          v-model:page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          v-model:current-page="page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import {
  getDishPage,
  dishStatusByStatus,
  deleteDish
} from '@/api/food'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据定义
const input = ref('')
const counts = ref(0)
const page = ref(1)
const pageSize = ref(10)
const tableData = ref([])
const checkList = ref([])

// 初始化数据
const init = async () => {
  const params = {
    page: page.value,
    pageSize: pageSize.value,
    name: input.value || undefined
  }

  try {
    const res = await getDishPage(params)
    if (res.code === 1) {
      tableData.value = res.data.records || []
      console.log(tableData.value)
      counts.value = res.data.total

    } else {
      ElMessage.error(res.msg || '请求失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 图片地址处理
const getImage = (image) => {
  return `/common/download?name=${image}`
}

// 搜索事件
const handleQuery = () => {
  page.value = 1
  init()
}

// 添加/编辑跳转
const addFoodtype = (st) => {
  if (st === 'add') {
    window.parent.menuHandle(
        { id: '4', url: '/backend/page/food/add.html', name: '添加菜品' },
        true
    )
  } else {
    window.parent.menuHandle(
        { id: '4', url: `/backend/page/food/add.html?id=${st}`, name: '修改菜品' },
        true
    )
  }
}

// 删除操作
const deleteHandle = async (type, id) => {
  if (type === '批量' && !id) {
    if (checkList.value.length === 0) {
      return ElMessage.error('请选择删除对象')
    }
    id = checkList.value.join(',')
  }

  try {
    await ElMessageBox.confirm('确认删除该菜品?', '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteDish({ ids: id })
    if (res.code === 1) {
      ElMessage.success('删除成功！')
      handleQuery()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 启售/停售
const statusHandle = async (row) => {
  let params = {}

  if (typeof row === 'string') {
    if (checkList.value.length === 0) {
      ElMessage.error('批量操作，请先勾选操作菜品！')
      return
    }
    params = { ids: checkList.value.join(','), status: row }
  } else {
    params = { ids: row.id, status: row.status === 0 ? 1 : 0 }
  }

  try {
    await ElMessageBox.confirm('确认更改该菜品状态?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await dishStatusByStatus(params)
    if (res.code === 1) {
      ElMessage.success('菜品状态更改成功！')
      handleQuery()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    ElMessage.error('请求出错了：' + err)
  }
}

// 多选监听
const handleSelectionChange = (val) => {
  checkList.value = val.map(v => v.id)
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  init()
}

const handleCurrentChange = (val) => {
  page.value = val
  init()
}

watchEffect(() => {
  init()
})
</script>

<style scoped>
.dashboard-container .notAdmin::after {
  border: 0 !important;
}
.continue {
  margin-left: 10px;
}
</style>
